package entities;

import java.util.Vector;

import message.MessageRelease;

import utils.Debug;
import visualisation.CompositionView;
import fragment.Fragment;

public class MMME {
	private String name;
	private Vector<Fragment> producerList=new Vector<Fragment>();
	private Vector<Fragment> reservationList=new Vector<Fragment>();
	private boolean givenByUser;

	public MMME(String name){
		this.name=name;
		givenByUser=true;
	}

	
	public MMME(String name,Fragment pro){
		this.name=name;
		givenByUser=false;
		producerList.add(pro);
		
		/**/
		Debug.println("MMME "+name+" : created");
		Debug.println("MMME "+name+" : new producer " + pro.getId());
	}

	
	public String getName(){
		return name;
	}
	
	public synchronized  void addProducer(Fragment pro){
		
		if(!producerList.contains(pro)){
			producerList.add(pro);
			
			synchronized(reservationList){
				for(Fragment f : reservationList)
					CompositionView.addLink(pro, f);
			}
		
			/**/
			Debug.println("MMME "+name+" : new producer " + pro.getId());
		}
	}
	
	public synchronized void removeProducer(Fragment pro){
		if(producerList.contains(pro)){
			producerList.remove(pro);
			
			synchronized(reservationList){
				for(Fragment f : reservationList)
					CompositionView.removeLink(pro, f);
			}
		
			/**/
			Debug.println("MMME "+name+" : end producer " + pro.getId());
		}
	}
	
	public synchronized Vector<Fragment> getProducerList(){
		return producerList;
	}
	
	public synchronized void addReservator(Fragment res){
		if(!reservationList.contains(res)){
			reservationList.add(res);
			
			synchronized(producerList){
				for(Fragment f : producerList)
					CompositionView.addLink(f, res);
			}
			
			/**/
			Debug.println("MMME "+name+" : new reservator " + res.getId());
		}
	}
	
	public synchronized void removeReservator(Fragment res){
		if(reservationList.contains(res)){
			reservationList.remove(res);
			
			synchronized(producerList){
				for(Fragment f : producerList)
					CompositionView.removeLink(f, res);
			}
			/**/
			Debug.println("MMME "+name+" : end reservator " + res.getId());
		}
	}
	
	public synchronized Vector<Fragment> getReservationList(){
		return reservationList;
	}

	public synchronized boolean isGivenByUser() {
		return givenByUser;
	}

	public synchronized void setGivenByUser(boolean givenByUser) {
		this.givenByUser = givenByUser;
	}
	
	public synchronized void delete(){		
		for(int i=0;i<reservationList.size();i++)
			//reservationList.get(i).release(this.name);
			reservationList.get(i).send(new MessageRelease(this.name));
		name="_deleted_"+name;
	}
}
